package com.common.utils.tools.http;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @Author liuyuan
 * @Date 2020-01-02 19:33
 * @Version 1.0
 */
public class HttpUtils {

    public static String requestJson(String url, Map<String, String> headers, String json, String charset) {
        HttpClientBuilder builder = HttpClientBuilder.create();
        CloseableHttpClient client = builder.build();
        HttpPost post = new HttpPost(url);
        if (StringUtils.isEmpty(charset)) {
            charset = "UTF-8";
        }
        post.addHeader("Accept", "application/json");
        post.addHeader("Content-Type", "application/json;charset=utf-8");
        if (headers != null && headers.size() > 0) {
            for (String key : headers.keySet()) {//keySet获取map集合key的集合  然后在遍历key即可
                String value = headers.get(key);
                post.addHeader(key, value);
            }
        }
        StringEntity requestEntity = null;
        requestEntity = new StringEntity(json, charset);
        post.setEntity(requestEntity);
        CloseableHttpResponse response = null;
        try {
            response = client.execute(post);
            HttpEntity entity = response.getEntity();
            return EntityUtils.toString(entity, "utf8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    //ly get请求
    public static String get(String url, Map<String, String> params, String charset) throws IOException {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        String body = null;
        String param = buildUrl(params);
        String action = url+"?"+param;
        HttpGet get = new HttpGet(action);
        body = invoke(httpclient, get, charset);

        httpclient.getConnectionManager().shutdown();

        return body;
    }
    private static String buildUrl(Map<String, String> params) {
        List<String> keys = new ArrayList<String>(params.keySet());
        Collections.sort(keys);
        String prestr = "";
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = params.get(key);
            if (i == keys.size() - 1) {
                // 拼接时，不包括最后一个&字符
                prestr = prestr + key + "=" + value;
            } else {
                prestr = prestr + key + "=" + value + "&";
            }
        }
        return prestr;
    }


    private static String invoke(DefaultHttpClient httpclient, HttpUriRequest httpost, String charset)
            throws IOException {

        HttpResponse response = sendRequest(httpclient, httpost);
        String body = paseResponse(response, charset);

        return body;
    }

    private static String paseResponse(HttpResponse response, String charset) {
        HttpEntity entity = response.getEntity();
        // String charset = EntityUtils.getContentCharSet(entity);
        String body = null;
        try {
            body = EntityUtils.toString(entity, charset);
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return body;
    }

    private static HttpResponse sendRequest(DefaultHttpClient httpclient, HttpUriRequest httpost) throws IOException {
        HttpResponse response = null;
        try {
            response = httpclient.execute(httpost);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            throw e;
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        }
        return response;
    }



}
